<template>
	<page-meta :page-style="themeColor"></page-meta>
	<view class="container">
		<view class="content">
			<view class="wx-code">
				<image :src="$util.img(path)" />
			</view>
			<view class="get-coupon">
				<text class="coupon-name">{{ info.coupon_name }}</text>
				<view class="color-base-text coupon-price" v-if="info.type == 'reward'">￥{{ info.money }}</view>
				<view class="color-base-text coupon-price" v-else-if="info.type == 'discount'">{{ info.discount }}折</view>
				<text v-if="info.at_least > 0" class="color-tip">满{{ info.at_least }}元使用</text>
				<text v-else class="color-tip">无门槛优惠券</text>
				<view v-if="info.validity_type == 0" class="color-tip">有效期至 {{ $util.timeStampTurnTime(info.end_time) }}</view>
				<view v-else-if="info.validity_type == 1" class="color-tip">领取之日起{{ info.fixed_term }}天内有效</view>
				<view v-else class="color-tip">长期有效</view>
				<!-- 适用场景： -->
				<view class="color-tip truncate" v-if="info.use_channel!='all'">{{ info.use_channel_name }}</view>
				<!-- 适用门店： -->
				<view v-if="info.use_channel!='online' &&info.use_store!='all'" class="color-tip">
					<view class="w-460 truncate">适用门店：{{ info.use_store_name}}</view>
				</view>
				<view class="get-span" @click="receiveGoodsCoupon(info.coupon_type_id)">
					<button type="primary" v-if="isCanReceive">{{ button }}</button>
					<button type="primary" disabled v-if="!isCanReceive">{{ button }}</button>
				</view>

				<view class="color-tip font-size-goods-tag tips">注:扫描二维码或点击右上角进行分享</view>
			</view>
		</view>
		<loading-cover ref="loadingCover"></loading-cover>
		<ns-login ref="login"></ns-login>
		<!-- 悬浮按钮 -->
		<hover-nav></hover-nav>

		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<privacy-popup ref="privacyPopup"></privacy-popup>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				info: {},
				couponTypeId: 0,
				path: '',
				button: '领取',
				uid: 0,
				couponBtnSwitch: false, //获取优惠券防止重复提交
				receivedNum: 0, 
				receivedType: ''
			};
		},
		onLoad(data) {
			setTimeout( () => {
				if (!this.addonIsExist.coupon) {
					this.$util.showToast({
						title: '商家未开启优惠券',
						mask: true,
						duration: 2000
					});
					setTimeout(() => {
						this.$util.redirectTo('/pages/index/index');
					}, 2000);
				}
			},1000);

			// #ifdef MP-ALIPAY
			let options = my.getLaunchOptionsSync();
			options.query && Object.assign(data, options.query)
			// #endif

			if (data.source_member) uni.setStorageSync('source_member', data.source_member);

			if (data.coupon_type_id) this.couponTypeId = data.coupon_type_id;

			// 小程序扫码进入
			if (data.scene) {
				var sceneParams = decodeURIComponent(data.scene);
				sceneParams = sceneParams.split('&');
				if (sceneParams.length) {
					sceneParams.forEach(item => {
						if (item.indexOf('coupon_type_id') != -1) this.couponTypeId = item.split('-')[1];
						if (item.indexOf('m') != -1) {
							this.source_member = item.split('-')[1];
							uni.setStorageSync('source_member', data.source_member);
						}
					});
				}
			}
		},
		onShow() {
			this.getCoupon();
			this.receivedNum = 0;
			if (this.storeToken) {
				//记录分享关系
				if (uni.getStorageSync('source_member')) {
					this.$util.onSourceMember(uni.getStorageSync('source_member'));
				}
				this.getReceivedNum();
			}
		},
		onHide() {
			this.couponBtnSwitch = false;
		},
		methods: {
			getCoupon() {
				this.$api.sendRequest({
					url: '/coupon/api/coupon/typeinfo',
					data: {
						coupon_type_id: this.couponTypeId
					},
					success: res => {
						let data = res.data;
						if (data) {
							this.info = data;
							this.path = data.qrcode;
							if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
							this.buttonRefresh();
							this.setPublicShare();
						} else {
							this.$util.showToast({
								title: res.message
							});
							setTimeout(() => {
								this.$util.redirectTo('/pages_tool/goods/coupon', {}, 'redirectTo');
							}, 1000);
						}
					},
					fail: res => {
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					}
				});
			},
			receiveGoodsCoupon(couponTypeId) {
				if (!this.storeToken) {
					this.$refs.login.open('/pages_tool/goods/coupon_receive?coupon_type_id=' + this.couponTypeId);
					return;
				}

				if (!this.isCanReceive) return;

				if (this.couponBtnSwitch) return;
				this.couponBtnSwitch = true;

				this.$api.sendRequest({
					url: '/coupon/api/coupon/receive',
					data: {
						coupon_type_id: couponTypeId,
						get_type: 2 //获取方式:1订单2.直接领取3.活动领取
					},
					success: res => {
						var data = res.data;
						let msg = res.message;
						this.receivedType = data.type;
						if (res.code == 0) {
							msg = '领取成功';
							this.receivedNum += 1;
						}
						this.buttonRefresh();
						this.$util.showToast({
							title: msg
						});
						this.couponBtnSwitch = false;
					},
					fail: res => {
						this.couponBtnSwitch = false;
					}
				});
			},
			getReceivedNum() {
				this.$api.sendRequest({
					url: '/coupon/api/coupon/receivedNum',
					data: {
						coupon_type_id: this.couponTypeId
					},
					success: res => {
						if (res.code >= 0) {
							this.receivedNum = res.data;
							this.buttonRefresh();
						}
					}
				});
			},
			buttonRefresh() {
				this.button = '领取';
				if (this.info.count <= this.info.lead_count || this.receivedType == 'out') {
					this.button = '来迟了该优惠券已被领取完了！';
				}
				if (this.info.status == 2 || this.receivedType == 'expire') {
					this.button = '该优惠券活动已结束！';
				}
				if (this.info.status == 3) {
					this.button = '该优惠券活动已关闭';
				}
				if (this.receivedType == 'limit'){
					this.button = '该优惠券领取已达到上限！';
				}
			},
			/**
			 * 设置公众号分享
			 */
			setPublicShare() {
				let shareUrl = this.$config.h5Domain + '/pages_tool/goods/coupon_receive?coupon_type_id=' + this.couponTypeId;
				if (this.memberInfo && this.memberInfo.member_id) shareUrl += '&source_member=' + this.memberInfo.member_id;

				var title = '';
				if (this.info.type == 'reward') {
					title = '恭喜您获得一张' + this.info.money + '元的优惠券';
				} else if (this.info.type == 'discount') {
					title = '恭喜您获得一张' + this.info.discount + '折优惠券';
				}
				if (this.info.at_least > 0) {
					var desc = `满${this.info.at_least}元可用`;
				} else {
					var desc = `无门槛优惠券`;
				}
				this.$util.setPublicShare({
					title: title,
					desc: desc,
					link: shareUrl,
					imgUrl: this.siteInfo ? this.$util.img(this.siteInfo.logo_square) : ''
				})

			}
		},
		computed: {
			isCanReceive: {
				get() {
					if (this.info.count <= this.info.lead_count || ['limit', 'expire', 'out'].includes(this.receivedType) || this.info.status == 2 || this.info.status == 3 ) {
						return false;
					}
					return true;
				}
			}
		},
		/**
		 * 自定义分享内容
		 * @param {Object} res
		 */
		onShareAppMessage(res) {
			var title = '';
			if (this.info.type == 'reward') {
				title = '恭喜您获得一张' + this.info.money + '元的优惠券';
			} else if (this.info.type == 'discount') {
				title = '恭喜您获得一张' + this.info.discount + '折优惠券';
			}
			if (this.info.at_least > 0) {
				title += `，满${this.info.at_least}元可用`;
			} else {
				title += `，无门槛优惠券`;
			}
			var path = '/pages_tool/goods/coupon_receive?coupon_type_id=' + this.couponTypeId;
			if (this.memberInfo && this.memberInfo.member_id) path += '&source_member=' + this.memberInfo.member_id;
			return {
				title: title,
				path: path,
				success: res => {},
				fail: res => {}
			};
		}
	};
</script>

<style lang="scss">
	page {
		height: 100%;
	}

	.container {
		background: #fff;
		padding: 0;
		height: 100vh;
	}

	.content {
		background: url() no-repeat;
		background-size: 100% auto;
		height: 100%;
	}

	.wx-code {
		position: relative;
		margin: 0 auto;
		top: 34%;
		width: 320rpx;
		height: 320rpx;
		text-align: center;
		padding: 14rpx;
		box-shadow: 0 0 40rpx -2rpx;
	}

	.wx-code image {
		width: 320rpx;
		height: 320rpx;
	}

	.get-coupon {
		position: relative;
		margin: 0 auto;
		width: 560rpx;
		top: 37%;
		text-align: center;
		height: 366rpx;

		.coupon-name {
			font-size: $font-size-toolbar;
		}
	}

	.get-span {
		text-align: center;
		display: block;
		border-radius: 6rpx;
		margin-top: 29px;
		margin-bottom: 20rpx;
		height: 80rpx;
		line-height: 80rpx;
		color: #fff;
	}

	.get-coupon .tips {
		height: 40rpx;
	}

	.coupon-price {
		font-size: 52rpx;
		height: 76rpx;
	}

	button {
		box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
	}
	.truncate {
		overflow: hidden;
		-o-text-overflow: ellipsis;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.color-tip{
		.w-460{
			width: 460rpx;
			margin: 0 auto;
			color: #909399 !important;
		}
		
	}
	// .color-tip.truncate{
	// 	text-align: left;
	// }
</style>